<template>
    <div class="station-type-container">
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="测站类型编码">
          <el-input v-model="searchForm.stationTypeCode" placeholder="请输入测站类型编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="测站类型名称">
          <el-input v-model="searchForm.stationTypeName" placeholder="请输入测站类型名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option :value="1" label="启用"></el-option>
            <el-option :value="0" label="禁用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button @click="resetSearchForm">重置</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增测站类型</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">批量删除</el-button>
      </div>
  
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :height="view.height - 430"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="stationTypeCode" label="测站类型编码" width="120"></el-table-column>
        <el-table-column prop="stationTypeName" label="测站类型名称" width="150"></el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="collectFrequency" label="数据采集频率" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="150">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页器 -->
      <el-pagination
        v-if="pagination.total > 0"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      ></el-pagination>
  
      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogType === 'add' ? '新增测站类型' : '编辑测站类型'"
        v-model="dialogVisible"
        width="500px"
      >
        <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
          <el-form-item label="类型编码" prop="stationTypeCode">
            <el-input 
              v-model="formData.stationTypeCode" 
              placeholder="请输入测站类型编码"
              :disabled="dialogType === 'edit'"
            ></el-input>
          </el-form-item>
          <el-form-item label="类型名称" prop="stationTypeName">
            <el-input v-model="formData.stationTypeName" placeholder="请输入测站类型名称"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input 
              v-model="formData.description" 
              type="textarea" 
              placeholder="请输入描述"
              :rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="采集频率" prop="collectFrequency">
            <el-input v-model="formData.collectFrequency" placeholder="请输入数据采集频率"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="formData.sortOrder" :min="1" placeholder="请输入排序号"></el-input-number>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="formData.remark" 
              type="textarea" 
              placeholder="请输入备注信息"
              :rows="2"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { defineComponent, reactive, ref, toRefs, onMounted, watch } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import axios from "axios";
  
  // 定义接口
  interface StationType {
    id: string;
    stationTypeCode: string;
    stationTypeName: string;
    description?: string;
    collectFrequency?: string;
    status: number;
    sortOrder?: number;
    remark?: string;
    createdAt: Date;
    updatedAt: Date;
  }
  
  // 表格数据
  const tableData = ref<StationType[]>([]);
  const selectedIds = ref<string[]>([]);
  
  // 分页数据
  const pagination = reactive({
    total: 0,
    pageNum: 1,
    pageSize: 10,
    totalPages: 0
  });
  
  // 搜索表单
  const searchForm = reactive({
    stationTypeCode: "",
    stationTypeName: "",
    status: null as number | null,
    collectFrequency: "",
    pageNum: 1,
    pageSize: 10
  });
  
  // 新增/编辑表单
  const formRef = ref();
  const formData = reactive({
    id: "",
    stationTypeCode: "",
    stationTypeName: "",
    description: "",
    collectFrequency: "",
    status: 1,
    sortOrder: 1,
    remark: ""
  });
  
  // 表单校验规则
  const formRules = {
    stationTypeCode: [
      { required: true, message: "请输入测站类型编码", trigger: "blur" },
      { max: 50, message: "长度不能超过50个字符", trigger: "blur" }
    ],
    stationTypeName: [
      { required: true, message: "请输入测站类型名称", trigger: "blur" },
      { max: 100, message: "长度不能超过100个字符", trigger: "blur" }
    ]
  };
  
  // 弹窗控制
  const dialogVisible = ref(false);
  const dialogType = ref<"add" | "edit">("add");
  
  // 视图高度
  const view = reactive({
    height: window.innerHeight,
  });
  window.onresize = function() {
    view.height = window.innerHeight;
  };
  
  // 加载数据
  const loadData = async () => {
    try {
      const params = {
        ...searchForm,
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize
      };
      
      const response = await axios.get('/algorithmApi/api1/station-type1/page', { params });
      if (response.data.code === 200) {
        tableData.value = response.data.data.list;
        pagination.total = response.data.data.total;
        pagination.totalPages = response.data.data.totalPages;
      } else {
        ElMessage.error(response.data.message || "获取数据失败");
      }
    } catch (error) {
      ElMessage.error("获取数据失败");
      console.error(error);
    }
  };
  
  // 重置搜索表单
  const resetSearchForm = () => {
    Object.keys(searchForm).forEach(key => {
      if (key !== "pageNum" && key !== "pageSize") {
        searchForm[key] = "";
      }
    });
    searchForm.status = null;
    pagination.pageNum = 1;
    loadData();
  };
  
  // 分页事件处理
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size;
    loadData();
  };
  
  const handleCurrentChange = (page: number) => {
    pagination.pageNum = page;
    loadData();
  };
  
  // 表格选择事件
  const handleSelectionChange = (selection: StationType[]) => {
    selectedIds.value = selection.map(item => item.id);
  };
  
  // 新增/编辑事件
  const handleAdd = () => {
    dialogType.value = "add";
    Object.keys(formData).forEach(key => {
      formData[key] = key === "status" ? 1 : key === "sortOrder" ? 1 : "";
    });
    dialogVisible.value = true;
  };
  
  const handleEdit = (row: StationType) => {
    dialogType.value = "edit";
    Object.keys(formData).forEach(key => {
      formData[key] = row[key] !== undefined ? row[key] : "";
    });
    dialogVisible.value = true;
  };
  
  // 表单提交
  const handleSubmit = async () => {
    formRef.value.validate(async (valid: boolean) => {
      if (!valid) return;
      
      try {
        let response;
        if (dialogType.value === "add") {
          response = await axios.post('/algorithmApi/api1/station-type1/', formData);
        } else {
          const { id, ...updateData } = formData;
          response = await axios.put(`/algorithmApi/api1/station-type1/${id}`, updateData);
        }
        
        if (response.data.code === 200) {
          ElMessage.success(response.data.message || "操作成功");
          dialogVisible.value = false;
          loadData();
        } else {
          ElMessage.error(response.data.message || "操作失败");
        }
      } catch (error) {
        ElMessage.error("操作失败");
        console.error(error);
      }
    });
  };
  
  // 删除处理
  const handleDelete = (row: StationType) => {
    ElMessageBox.confirm(`确定要删除测站类型"${row.stationTypeName}"吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      try {
        const response = await axios.delete(`/algorithmApi/api1/station-type1/${row.id}`);
        if (response.data.code === 200) {
          ElMessage.success(response.data.message || "删除成功");
          loadData();
        } else {
          ElMessage.error(response.data.message || "删除失败");
        }
      } catch (error) {
        ElMessage.error("删除失败");
        console.error(error);
      }
    }).catch(() => {});
  };
  
  // 批量删除
  const handleBatchDelete = () => {
    if (selectedIds.value.length === 0) {
      ElMessage.warning("请至少选择一条记录");
      return;
    }
    
    ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}条记录吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      try {
        const response = await axios.delete('/algorithmApi/api1/station-type1/batch', {
          data: { ids: selectedIds.value }
        });
        if (response.data.code === 200) {
          ElMessage.success(response.data.message || "批量删除成功");
          loadData();
        } else {
          ElMessage.error(response.data.message || "批量删除失败");
        }
      } catch (error) {
        ElMessage.error("批量删除失败");
        console.error(error);
      }
    }).catch(() => {});
  };
  
  // 状态变更
  const handleStatusChange = async (row: StationType) => {
    const newStatus = row.status === 1 ? 0 : 1;
    const statusText = newStatus === 1 ? "启用" : "禁用";
    
    try {
      const response = await axios.put(`/algorithmApi/api1/station-type1/${row.id}/status`, {
        status: newStatus
      });
      if (response.data.code === 200) {
        ElMessage.success(`${statusText}成功`);
        loadData();
      } else {
        ElMessage.error(response.data.message || `${statusText}失败`);
      }
    } catch (error) {
      ElMessage.error(`${statusText}失败`);
      console.error(error);
    }
  };
  
  // 日期格式化
  const formatDate = (date: Date | string) => {
    if (!date) return "";
    const d = new Date(date);
    
    const pad = (num: number) => num.toString().padStart(2, '0');
    
    const year = d.getFullYear();
    const month = pad(d.getMonth() + 1);
    const day = pad(d.getDate());
    const hours = pad(d.getHours());
    const minutes = pad(d.getMinutes());
    const seconds = pad(d.getSeconds());
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  
  // 页面加载
  onMounted(() => {
    loadData();
  });
  </script>
  
  <style lang="scss" scoped>
  .station-type-container {
    padding: 20px;
    
    .search-form {
      margin-bottom: 20px;
      padding: 20px;
      border-radius: 4px;
    }
    
    .toolbar {
      margin-bottom: 20px;
      display: flex;
      justify-content: flex-start;
      gap: 10px;
    }
    
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
  </style>
  